package com.mql.ganio.ui.presenter;

import android.text.TextUtils;

import com.mql.ganio.api.ApiRetrofit;
import com.mql.ganio.app.ConstantsImageUrl;
import com.mql.ganio.model.bean.AndroidBean;
import com.mql.ganio.model.response.EveryDayResponse;
import com.mql.ganio.model.response.FrontpageResponse;
import com.mql.ganio.ui.adapter.EverydayAdapter;
import com.mql.ganio.ui.base.BaseActivity;
import com.mql.ganio.ui.base.BasePresenter;
import com.mql.ganio.ui.view.IGanHuoAtView;
import com.mql.ganio.util.GlideImageLoader;
import com.mql.ganio.util.SPUtils;
import com.mql.ganio.util.TimeUtil;
import com.youth.banner.listener.OnBannerClickListener;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;

import rx.Observable;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 作者：Administrator on 2017/11/10 11:02
 */
public class EveryDayAtPresenter extends BasePresenter<IGanHuoAtView> {
    private ArrayList<String> mBannerImages;
    BaseActivity context;
    private static final String HOME_ONE = "home_one";
    private static final String HOME_TWO = "home_two";
    private static final String HOME_SIX = "home_six";
    EverydayAdapter mEverydayAdapter;

    public EveryDayAtPresenter(BaseActivity context) {
        super(context);
        this.context = context;
    }

    public void getBannerData() {
        mContext.showWaitingDialog("加载中...");
        ApiRetrofit.getInstance()
                .getBannerData()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<FrontpageResponse>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onNext(FrontpageResponse frontpageResponse) {
                        //  frontpageResponse.getResult().getFocus();

                        if (frontpageResponse != null && frontpageResponse.getResult() != null && frontpageResponse.getResult().getFocus() != null && frontpageResponse.getResult().getFocus().getResult() != null) {
                            final List<FrontpageResponse.ResultBeanXXXXXXXXXXXXXX.FocusBean.ResultBeanX> result = frontpageResponse.getResult().getFocus().getResult();
                            if (result != null && result.size() > 0) {
                                for (int i = 0; i < result.size(); i++) {
                                    //获取所有图片
                                    mBannerImages.add(result.get(i).getRandpic());
                                }
                                getView().getBanner().setImages(mBannerImages).setImageLoader(new GlideImageLoader()).start();
                                getView().getBanner().setOnBannerClickListener(new OnBannerClickListener() {
                                    @Override
                                    public void OnBannerClick(int position) {
                                        position = position - 1;
                                        // 链接没有做缓存，如果轮播图使用的缓存则点击图片无效
//                                        if (result.get(position) != null && result.get(position).getCode() != null
//                                                && result.get(position).getCode().startsWith("http")) {
//                                            WebViewActivity.loadUrl(getContext(), result.get(position).getCode(), "加载中...");
//                                        }
                                    }
                                });

                            }
                        }
                    }
                });
        mContext.hideWaitingDialog();
    }

    public void refreshData() {
        mContext.showWaitingDialog("加载中...");
        Func1<EveryDayResponse, Observable<List<List<AndroidBean>>>> func1 = new Func1<EveryDayResponse, Observable<List<List<AndroidBean>>>>() {
            @Override
            public Observable<List<List<AndroidBean>>> call(EveryDayResponse gankIoDayBean) {

                List<List<AndroidBean>> lists = new ArrayList<>();
                EveryDayResponse.ResultsBean results = gankIoDayBean.getResults();

                if (results.getAndroid() != null && results.getAndroid().size() > 0) {
                    addUrlList(lists, results.getAndroid(), "Android");
                }
                if (results.get福利() != null && results.get福利().size() > 0) {
                    addUrlList(lists, results.get福利(), "福利");
                }
                if (results.getiOS() != null && results.getiOS().size() > 0) {
                    addUrlList(lists, results.getiOS(), "IOS");
                }
                if (results.get休息视频() != null && results.get休息视频().size() > 0) {
                    addUrlList(lists, results.get休息视频(), "休息视频");
                }
                if (results.get拓展资源() != null && results.get拓展资源().size() > 0) {
                    addUrlList(lists, results.get拓展资源(), "拓展资源");
                }
                if (results.get瞎推荐() != null && results.get瞎推荐().size() > 0) {
                    addUrlList(lists, results.get瞎推荐(), "瞎推荐");
                }
                if (results.get前端() != null && results.get前端().size() > 0) {
                    addUrlList(lists, results.get前端(), "前端");
                }
                if (results.getApp() != null && results.getApp().size() > 0) {
                    addUrlList(lists, results.getApp(), "App");
                }

                return Observable.just(lists);
            }
        };
        ApiRetrofit.getInstance()
                .getEveryDayData(getTodayTime().get(0),
                        getTodayTime().get(1),
                        getTodayTime().get(2)).
                subscribeOn(Schedulers.io()).
                observeOn(AndroidSchedulers.mainThread())
                .flatMap(func1)
                .subscribe(new Observer<List<List<AndroidBean>>>() {

                               @Override
                               public void onCompleted() {

                               }

                               @Override
                               public void onError(Throwable e) {

                               }

                               @Override
                               public void onNext(List<List<AndroidBean>> lists) {
                                   if (lists.size() > 0 && lists.get(0).size() > 0) {
                                       setAdapter(lists);
                                   }
                               }

                           }

                );
        mContext.hideWaitingDialog();
    }

    private void setAdapter(List<List<AndroidBean>> lists) {
        if (mEverydayAdapter == null) {
            mEverydayAdapter = new EverydayAdapter(context, lists);
        } else {
            mEverydayAdapter.clear();
        }
        mEverydayAdapter.setDatas(lists);
        getView().getXRecyclerView().setAdapter(mEverydayAdapter);
    }

    /**
     * 获取当天日期
     */
    private ArrayList<String> getTodayTime() {
        String data = TimeUtil.getData();
        String[] split = data.split("-");
        String year = split[0];
        String month = split[1];
        String day = split[2];
        ArrayList<String> list = new ArrayList<>();
        list.add(year);
        list.add(month);
        list.add(day);
        return list;
    }


    // subList没有实现序列化！缓存时会出错！
    private void addUrlList(List<List<AndroidBean>> lists, List<AndroidBean> arrayList, String typeTitle) {
        // title
        AndroidBean bean = new AndroidBean();
        bean.setType_title(typeTitle);
        ArrayList<AndroidBean> androidBeen = new ArrayList<>();
        androidBeen.add(bean);
        lists.add(androidBeen);

        int androidSize = arrayList.size();

        if (androidSize > 0 && androidSize < 4) {

            lists.add(addUrlList(arrayList, androidSize));
        } else if (androidSize >= 4) {

            ArrayList<AndroidBean> list1 = new ArrayList<>();
            ArrayList<AndroidBean> list2 = new ArrayList<>();

            for (int i = 0; i < androidSize; i++) {
                if (i < 3) {
                    list1.add(getAndroidBean(arrayList, i, androidSize));
                } else if (i < 6) {
                    list2.add(getAndroidBean(arrayList, i, androidSize));
                }
            }
            lists.add(list1);
            lists.add(list2);
        }
    }

    private AndroidBean getAndroidBean(List<AndroidBean> arrayList, int i, int androidSize) {

        AndroidBean androidBean = new AndroidBean();
        // 标题
        androidBean.setDesc(arrayList.get(i).getDesc());
        // 类型
        androidBean.setType(arrayList.get(i).getType());
        // 跳转链接
        androidBean.setUrl(arrayList.get(i).getUrl());
        // 随机图的url
        if (i < 3) {
            androidBean.setImage_url(ConstantsImageUrl.HOME_SIX_URLS[getRandom(3)]);//三小图
        } else if (androidSize == 4) {
            androidBean.setImage_url(ConstantsImageUrl.HOME_ONE_URLS[getRandom(1)]);//一图
        } else if (androidSize == 5) {
            androidBean.setImage_url(ConstantsImageUrl.HOME_TWO_URLS[getRandom(2)]);//两图
        } else if (androidSize >= 6) {
            androidBean.setImage_url(ConstantsImageUrl.HOME_SIX_URLS[getRandom(3)]);//三小图
        }
        return androidBean;
    }


    private List<AndroidBean> addUrlList(List<AndroidBean> arrayList, int androidSize) {
        List<AndroidBean> tempList = new ArrayList<>();
        for (int i = 0; i < androidSize; i++) {
            AndroidBean androidBean = new AndroidBean();
            // 标题
            androidBean.setDesc(arrayList.get(i).getDesc());
            // 类型
            androidBean.setType(arrayList.get(i).getType());
            // 跳转链接
            androidBean.setUrl(arrayList.get(i).getUrl());
//            DebugUtil.error("---androidSize:  " + androidSize);
            // 随机图的url
            if (androidSize == 1) {
                androidBean.setImage_url(ConstantsImageUrl.HOME_ONE_URLS[getRandom(1)]);//一图
            } else if (androidSize == 2) {
                androidBean.setImage_url(ConstantsImageUrl.HOME_TWO_URLS[getRandom(2)]);//两图
            } else if (androidSize == 3) {
                androidBean.setImage_url(ConstantsImageUrl.HOME_SIX_URLS[getRandom(3)]);//三图
            }
            tempList.add(androidBean);
        }
        return tempList;
    }

    /**
     * 取不同的随机图，在每次网络请求时重置
     */
    private int getRandom(int type) {
        String saveWhere = null;
        int urlLength = 0;
        if (type == 1) {
            saveWhere = HOME_ONE;
            urlLength = ConstantsImageUrl.HOME_ONE_URLS.length;
        } else if (type == 2) {
            saveWhere = HOME_TWO;
            urlLength = ConstantsImageUrl.HOME_TWO_URLS.length;
        } else if (type == 3) {
            saveWhere = HOME_SIX;
            urlLength = ConstantsImageUrl.HOME_SIX_URLS.length;
        }

        String home_six = SPUtils.getInstance(context).getString(saveWhere, "");
        if (!TextUtils.isEmpty(home_six)) {
            // 已取到的值
            String[] split = home_six.split(",");

            Random random = new Random();
            for (int j = 0; j < urlLength; j++) {
                int randomInt = random.nextInt(urlLength);

                boolean isUse = false;
                for (String aSplit : split) {
                    if (!TextUtils.isEmpty(aSplit) && String.valueOf(randomInt).equals(aSplit)) {
                        isUse = true;
                        break;
                    }
                }
                if (!isUse) {
                    StringBuilder sb = new StringBuilder(home_six);
                    sb.insert(0, randomInt + ",");
                    SPUtils.getInstance(context).putString(saveWhere, sb.toString());
                    return randomInt;
                }
            }

        } else {
            Random random = new Random();
            int randomInt = random.nextInt(urlLength);
            SPUtils.getInstance(context).putString(saveWhere, randomInt + ",");
            return randomInt;
        }
        return 0;
    }
}
